import config from "@/config/config.js";
import cookie from "@/util/store/cookie.js";

import Vue from 'vue';
import store from "@/store/index.js";

import {
	getMessageList
} from "@/service/messageService.js";

const timeout = "3000";
let timeoutObj = null;

// 判断是否已连接
const checkOpenSocket = function() {
	uni.sendSocketMessage({
		data: JSON.stringify({
			controller: "Index",
			action: "onOpen",
			param: {
				userId: cookie.get('sid')
			}
		}),
		success: res => {
			return;
		},
		fail: err => {
			// 未连接打开websocket连接
			connectSocket();
		}
	});
}

const connectSocket = function() {
	const token = cookie.get('token');
	if (token == '') return;
	uni.connectSocket({
		url: config.webSocketRoot + "?token=" + token,
		data() {
			return {
				x: '',
				y: ''
			};
		},
		header: {
			'content-type': 'application/json'
		},
		protocols: ['protocol1'],
		method: 'GET',
		success(res) {
			console.log('连接成功 connectSocket=', res);
		},
		fail(err) {
			console.log('连接失败 connectSocket=', err);
		}
	});
	uni.onSocketOpen(function(res) {
		console.log('WebSocket连接已打开！');
		uni.sendSocketMessage({
			data: JSON.stringify({
				controller: "Index",
				action: "onOpen",
				param: {
					userId: cookie.get('sid')
				}
			}),
			success(res) {
				console.log('发送成功 sendMessage=', res);
			},
			fail(err) {
				console.log('发送失败 sendMessage=', err);
			}
		})
	});
	receive();
}

const sendMess = function(param) {
	var socketOpen = false;

	uni.sendSocketMessage({
		data: JSON.stringify({
			controller: "Index",
			action: "send",
			param: {
				param: param
			}
		}),
		success() {
			setTimeout(() => {
				getMessageList().then(getFriendsList)
			}, 1500);

		}
	})

	//console.log(socketOpen)
}

const receive = function() {
	Vue.prototype.$store = store;
	let param = '';
	uni.onSocketMessage(function(res) {
		// console.log(res);
		if (res.data !== null && res.data !== '' && res.data !== 'null') {

			let routes = getCurrentPages() //获取当前页面栈
			let curRoute = routes[routes.length - 1].route //获取当前页面的路由
			console.log(curRoute);
			var param = JSON.parse(res.data);
			store.commit("addMssageNum");
			var str = param.sid;
			var list = {};
			list[str] = param;
			let message = store.state.messageList;
			message.push(param);
			store.state.messageList = message;
			console.log('收到消息播放声音');
			const innerAudioContext = uni.createInnerAudioContext();
			innerAudioContext.autoplay = true;
			innerAudioContext.src = 'https://downsc.chinaz.net/Files/DownLoad/sound1/201706/8858.mp3';
			innerAudioContext.play();
			console.log('收到消息振动');
			uni.vibrateLong();
			console.log('收到服务器内容：' + res.data);
			getMessageList().then(getFriendsList)
		}
	})
	reset();
	return param;
}

const getFriendsList = function(e) {
	if (e.code == 200) {
		store.state.friendList = e.result.data;
		store.state.messageNum = e.result.total;
	}
}

// 检测心跳reset
const reset = function() {
	// console.log('检测心跳')
	clearInterval(timeoutObj);
	start(); // 启动心跳
}

// 启动心跳 start
const start = function() {
	// console.log('启动心跳')
	timeoutObj = setInterval(function() {
		uni.sendSocketMessage({
			data: JSON.stringify({
				controller: "Index",
				action: "onOpen",
				param: {
					userId: cookie.get('sid')
				}
			}),
			success: res => {
				// console.log('启动心跳成功....');
			},
			fail: err => {
				console.log('连接失败重新连接....');
				connectSocket();

			}
		});
	}, timeout);
}

export default {
	timeout,
	timeoutObj,
	checkOpenSocket,
	connectSocket,
	sendMess,
	receive,
	reset,
	start,
	getFriendsList
}
